<!-- 人事异动-待异动 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="待异动" :showBack="false"></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <div style="display: flex">
            <a-select :options="options" v-model="keyWold" />
            <a-input-search
              @press-enter="search"
              @search="search"
              v-model="keyWoldValue"
              placeholder="请输入"
            />
          </div>
          <a-input-search
            @press-enter="search"
            @search="search"
            v-model="phoneData"
            placeholder="输入手机号码搜索"
          />
          <a-button @click="reset">重置</a-button>
        </a-space>
      </template>
      <template #right>
        <a-button type="primary" @click="humanModalVisible = true"
          >办理异动</a-button
        >
        <a-button type="outline" @click="importVisible = true">导入</a-button>
        <a-button type="outline" @click="exportSettingVisible = true"
          >导出</a-button
        >
        <a-dropdown
          @select="moreControl"
          @popup-visible-change="handleBatchVisible"
          v-model:popup-visible="showBatch"
        >
          <a-button type="outline">批量操作</a-button>
          <template #content>
            <a-doption :value="1">撤销</a-doption>
            <a-doption :value="2">确认</a-doption>
          </template>
        </a-dropdown>
      </template>
    </ConditionBox>
    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="姓名" data-index="name">
      </a-table-column>
      <a-table-column :width="150" title="工号" data-index="jobNum">
      </a-table-column>
      <a-table-column :width="150" title="新部门" data-index="department">
        <template #cell="{ record }">
          {{ dataList?.organizationList.find((el: any) => el.id == record.department)?.name }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="新职位" data-index="position">
        <template #cell="{ record }">
          {{ dataList?.positionList.find((el: any) => el.id == record.position)?.name }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="异动类型" data-index="type">
        <template #cell="{ record }">
          {{ TRANSACTION.find((el: any) => el.id == record.type)?.label }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="异动原因" data-index="reason">
        <template #cell="{ record }">
          {{ dataList?.transactionTypeList?.find((el: any) => el.id == record.reason)?.reason }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="生效日期" data-index="effectTime">
      </a-table-column>
      <a-table-column
        :width="150"
        title="办理日期"
        data-index="applicationTime"
      ></a-table-column>
      <a-table-column :width="150" title="审批编号" data-index="">
      </a-table-column>
      <a-table-column :width="150" title="审批状态" data-index="">
      </a-table-column>
      <a-table-column :width="150" fixed="right" title="操作">
        <template #cell="{ record }">
          <a-popconfirm content="确认办理该条异动吗？" @ok="confirm(record)">
            <a-button type="text">确认</a-button>
          </a-popconfirm>
          <a-tooltip content="查看详情">
            <icon-font
              type="icon-details-def"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>
          <a-tooltip content="撤销">
            <icon-font
              type="icon-chexiao"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
              @click="cancel(record)"
            />
          </a-tooltip>
          <a-tooltip content="更多功能">
            <a-dropdown
              @select="(value: number, e: Event, id: number) => moreItemControl(value, e, record.id)"
            >
              <icon-font
                type="icon-more-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="singleControl(record)"
              />
              <template #content>
                <a-doption :value="1">解除劳动合同</a-doption>
                <a-doption :value="2">延长试用期</a-doption>
                <a-doption :value="3">调岗处理</a-doption>
                <a-doption :value="4">转正申请</a-doption>
              </template>
            </a-dropdown>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <HumanRosterModal
    style="z-index: 9999"
    v-model:visible="humanModalVisible"
    @humanRosterEmit="humanRosterEmit"
    typeName="5"
  ></HumanRosterModal>
</template>
<script setup lang="tsx">
import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';
import TableTurn, { type paramsType } from '@/components/TableTurn/index.vue';
import { Modal, Button } from '@arco-design/web-vue';
import { getListData, IneedSwitchArr } from '@/utils/getAllSwitchListData';
import dayjs from 'dayjs';
import clonedeep from 'lodash.clonedeep';
import { TRANSACTION } from '@/utils/constants';
import {
  ConfirmSendTransaction,
  GetTransactionLatestDetail,
  PutTransaction,
  GetTransactionRecordList,
  DelTransaction
} from '@/apis/management/personnel/changeManagement/transactionManagement';

const userId = +(localStorage.getItem('userId') as string);

let humanModalVisible = ref(false); // 发起人事异动弹出框
// 选择异动人员弹出框自定义事件
const humanRosterEmit = (record: any) => {
  router.push({
    name: 'HandleTransaction',
    query: { id: record.id }
  });
};

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true
});
let tableRef = ref();
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);
const router = useRouter();

const getTableData = async (pageData: any) => {
  try {
    const res = await GetTransactionRecordList({
      isDone: 2,
      ...pageData
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

const needSwitchArr: IneedSwitchArr[] = [
  'organization',
  'position',
  'transactionType'
];
const dataList = ref(); // 储存要转换的数据列表
const init = async () => {
  try {
    dataList.value = await getListData(needSwitchArr);
  } catch (error: unknown) {
    console.log(error);
  }
};
init();

const goDetail = (data: any) => {
  router.push({
    name: 'HandleTransaction',
    query: { id: data.id }
  });
};

let showBatch = ref(false);
// 批量操作
const handleBatchVisible = () => {
  if (selectedList.value.length === 0) {
    Message.error('请先选择数据');
    showBatch.value = false;
    return;
  }
};

// 批量操作
const moreControl = (key: number) => {
  switch (key) {
    case 1:
      moreItemControl(5, '撤销异动');
      break;
    case 2:
      moreItemControl(6, '确认异动办理');
      break;
    default:
      break;
  }
};

let singleSelectId = 0; // 储存单个item移动、合并的id
let singleSelectData = {}; // 储存单个item移动、合并的值
// 点击三个小点事件
const singleControl = (record: any) => {
  singleSelectData = record;
  singleSelectId = record.id;
};

// 确认
const confirm = async (record: any) => {
  try {
    // const res = await GetTransactionLatestDetail({
    //   id
    // });
    const switch2NumberEnums = ['type', 'reason', 'id', 'userId'];
    const temp = clonedeep(record);
    for (let i in record) {
      if (!switch2NumberEnums.includes(i)) {
        temp[i] = temp[i] + '';
      }
    }
    temp.id = record.userId;
    temp.transactorId = userId;
    temp.isDone = 1;
    temp.applicationTime = dayjs().format('YYYY-MM-DD');
    record.transactorId = userId;
    record.isDone = 1;
    record.applicationTime = dayjs().format('YYYY-MM-DD');
    await ConfirmSendTransaction(temp);
    await PutTransaction(record);
    // await ChangeHumanInductionState({
    //   ids: [id],
    //   type: 5
    // });
    Message.success('确认成功！');
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 表格中的三个小点按钮的下拉菜单
const moreItemControl = async (key: number, e: Event | string, id?: number) => {
  try {
    let title = e?.target?.innerText || e;
    let content: any;
    let onOk: (() => void) | undefined;
    switch (key) {
      case 1:
        // EntryNotice(id);
        break;
      case 2:
        content = <>是否跳转到试用期列表延长试用期时间？</>;
        onOk = () => {
          router.push({
            name: 'ProbationPeriodManagement'
          });
        };
        break;
      // case 3:
      //   content = <></>;
      //   onOk = async () => {
      //     await ChangeHumanInductionState({
      //       ids: selectedList.value.length > 0 ? selectedList.value : [id],
      //       type: 4
      //     });
      //     refresh();
      //   };
      //   break;
      // case 4:
      //   content = (
      //     <>
      //       <a-form model={model} autoLabelWidth>
      //         <a-form-item field="name" label="选择审批模板">
      //           <a-select placeholder="请选择审批模板" />
      //         </a-form-item>
      //       </a-form>
      //     </>
      //   );
      //   onOk = async () => {
      //     refresh();
      //   };
      //   break;
      case 5:
        content = <>是否确认撤销选中的异动？</>;
        onOk = async () => {
          await DelTransaction({
            ids: selectedList.value.length > 0 ? selectedList.value : [id]
          });
          Message.success('撤销成功！');
          refresh();
        };
        break;
      case 6:
        content = <>是否确认办理选中的异动？</>;
        onOk = async () => {
          const switch2NumberEnums = ['type', 'reason', 'id', 'userId'];
          for (let i = 0; i < selectedListData.value.length; i++) {
            const temp = clonedeep(selectedListData.value[i]);
            for (let j in selectedListData.value[i]) {
              if (!switch2NumberEnums.includes(j)) {
                temp[j] = temp[j] + '';
              }
            }
            temp.id = selectedListData.value[i].userId;
            temp.transactorId = userId;
            temp.isDone = 1;
            temp.applicationTime = dayjs().format('YYYY-MM-DD');
            selectedListData.value[i].transactorId = userId;
            selectedListData.value[i].isDone = 1;
            selectedListData.value[i].applicationTime =
              dayjs().format('YYYY-MM-DD');
            await ConfirmSendTransaction(temp);
            await PutTransaction(selectedListData.value[i]);
          }
          Message.success('确认成功！');
          refresh();
        };

        break;
      default:
        break;
    }
    // 如果不用弹出框就直接return，用于跳转的发送入职通知
    if (!onOk) return;
    Modal.open({
      title,
      content,
      width: '50%',
      onOk
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 模糊查询参数
const options = reactive([
  { label: '姓名', value: 'name' },
  { label: '职位', value: 'positionName' }
]);
// 模糊类型
const keyWold = ref('name');
// 模糊查询值
const keyWoldValue = ref('');

const phoneData = ref('');
const search = () => {
  refresh();
};

// 重置数据
const reset = () => {
  keyWold.value = 'name';
  keyWoldValue.value = '';
  phoneData.value = '';
  refresh();
};

// 刷新列表
const refresh = (page?: any) => {
  tableRef.value.loadData(page);
};
</script>
<style lang="less" scoped>
.wrap {
  padding: 10px 20px;

  // 弄出一个小的圆形
}
</style>
